import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/models/xindong_file_select_class.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/dialog/xindong_options_sheet.dart';
import 'package:xindong/widgets/image/xindong_media_add_preview.dart';

import 'image_grid/xindong_image_grid_view.dart';

// 媒体类型
enum MediaType {
  image, // 图片
  video, // 视频
}

// 支持媒体类型
enum MediaSupportType {
  all, // 图片+视频
  onlyImage, // 图片
  onlyVideo, // 视频
}

// 类型定义（回调图片文件模型数组/视频文件模型）
typedef XinDongMediaAdditionFunction = void Function(
  List<XinDongSelectFileClass>? images,
  XinDongSelectFileClass? video,
);

class XinDongMediaAddController extends GetxController {
  static XinDongMediaAddController get to => Get.find();

  // 发布的图片File数组（不能直接上传，要取路径上传）
  List<XinDongSelectFileClass> fileList = [];
  int maxCount = 0;
  MediaType? selectType;
  MediaSupportType supportType = MediaSupportType.all;

  // 回调方法
  XinDongMediaAdditionFunction? onSelect;

  // 判断选择的是否有视频
  bool get haveVideo {
    return fileList.any((element) => !TextUtil.isEmpty(element.videoPath));
  }

  // 调用添加图片/视频
  void onTapAddition() async {
    FocusScope.of(currentContext()).requestFocus(FocusNode());
    // 支持视频（有视频回调，且还没上传过文件）
    switch (supportType) {
      case MediaSupportType.onlyImage:
        _addPhotos();
        break;
      case MediaSupportType.onlyVideo:
        _addVideo();
        break;
      default:
        {
          final dataList = ["发视频", "发照片"];
          MediaType? type;
          await XinDongOptionsSheet.showAwait(
            dataList: dataList,
            onSelect: (int index) {
              if (index == 0) {
                type = MediaType.video;
              } else {
                type = MediaType.image;
              }
            },
          );
          if (type == null) {
            return;
          }
          if (type == MediaType.image) {
            _addPhotos(); // 照片
          } else if (type == MediaType.video) {
            _addVideo();
          }
        }
        break;
    }
  }

  // 添加图片
  void _addPhotos() async {
    selectType = MediaType.image;
    // 可添加数量为最大数-已添加数
    List<File>? resultList = await ImageUtil.selectPhotos(maxCount: (maxCount - fileList.length));
    if (resultList != null && resultList.isNotEmpty) {
      List<XinDongSelectFileClass> models = [];
      for (File file in resultList) {
        XinDongSelectFileClass model = await ImageUtil.getImageSizeWithFile(file);
        models.add(model);
      }
      fileList.addAll(models);
      update();
      mDebugPrint("图片尺寸 $models");
      // 响应数据回调
      if (onSelect != null) onSelect!(fileList, null);
    }
  }

  // 添加视频
  void _addVideo() async {
    selectType = MediaType.video;
    // 可添加数量为1个视频
    Media? result = await ImageUtil.selectVideo();
    if (result != null && result.thumbPath != null) {
      XinDongSelectFileClass model = await ImageUtil.getImageSizeWithFile(File(result.thumbPath!));
      model.videoPath = result.path; // 视频路径
      fileList = [model];
      update();
      // 响应数据回调
      if (onSelect != null) onSelect!(null, model);
    }
  }

// 调用删除图片
  void onTapDeletion(int index) {
    if (fileList.length > index) {
      fileList.removeAt(index);
      update();
      // 响应数据回调
      if (onSelect != null) {
        onSelect!(
          selectType == MediaType.image ? fileList : null,
          selectType == MediaType.video ? fileList.first : null,
        );
      }
    }
  }
}

class XinDongMediaAddContainer extends StatelessWidget {
  final int maxCount;
  final int columns;
  final double spacing;
  final double radius;
  final MediaSupportType supportType;
  final EdgeInsetsGeometry? padding; // 填充

  // 回调方法
  final XinDongMediaAdditionFunction onSelect;

  XinDongMediaAddContainer({
    Key? key,
    this.maxCount = 9,
    this.columns = 3,
    this.spacing = 8.0,
    this.radius = 8.0,
    this.supportType = MediaSupportType.all,
    this.padding,
    required this.onSelect,
  }) : super(key: key) {
    final controller = Get.put(XinDongMediaAddController());
    controller.maxCount = maxCount;
    controller.supportType = supportType;
    controller.onSelect = onSelect;
  }

  static delete() {
    Get.delete<XinDongMediaAddController>();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<XinDongMediaAddController>(builder: (controller) {
      return MediaQuery.removePadding(
        removeTop: true,
        removeBottom: true,
        context: context,
        child: XinDongImageGridView(
          dataList: controller.fileList,
          padding: padding,
          spacing: spacing,
          radius: radius,
          columns: columns,
          maxCount: maxCount,
          onTapAddition: controller.haveVideo ? null : controller.onTapAddition,
          itemBuilder: (BuildContext context, int index) {
            XinDongSelectFileClass model = controller.fileList[index];
            return XinDongMediaAddPreview(
              model: model,
              onTapDeletion: () => controller.onTapDeletion(index),
            );
          },
        ),
      );
    });
  }
}
